<?php

namespace app\service;

//气球旅行服务
use app\model\UserStaff;
use app\model\UserTravel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserTravelService extends BaseService
{


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_user_travel($user_id): array
    {
        $user_travel = (new UserTravel())->where('user_id', $user_id)->find();
        return $this->returnSuccess($user_travel);
    }


    /**
     * @throws DbException
     */
    public function start($user_id, $role_ids): array
    {
        //用_分割
        $role_ids = explode('_', $role_ids);
        //不能小于三个人
        if (count($role_ids) < TRAVEL_ROLE_NUM) {
            return $this->returnFail('至少选择三个角色');
        }

        //获取角色信息
        $user_role_count = (new UserStaff())->where('user_id', $user_id)->whereIn('staff_id', $role_ids)->count();

        if ($user_role_count < TRAVEL_ROLE_NUM) {
            return $this->returnFail('角色未拥有');
        }


        //创建旅行
        $user_travel = new UserTravel();


        $user_travel->user_id = $user_id;
        $user_travel->extra = implode(',', $role_ids);


        //稍后计算奖励
        $reward = [];

        //将获得的奖励
        $user_travel->reward = $reward;
        $user_travel->status = TRAVEL_STATUS['旅行中'];
        $user_travel->save();
        return $this->returnSuccess($user_travel);

    }


    //完成旅行

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function complete($user_id, $user_travel_id): array
    {

        $user_travel = (new UserTravel())->where('user_id',$user_id)->where('id',$user_travel_id)->find();
        if(!$user_travel){
            return $this->returnFail('旅行事件不存在');
        }

        //判断是否完成
        if ($user_travel->status == TRAVEL_STATUS['旅行中']) {
            return  $this->returnFail('旅行未完成');
        }

        if ($user_travel->state == TRAVEL_STATE['已发放']) {
            return  $this->returnFail('奖励已领取');
        }

        //发放奖励
        $reward = json_decode($user_travel->reward,true);




        //完成旅行
        $user_travel->state = TRAVEL_STATE['已发放'];

        $res = $user_travel->save();

        if($res){
            return $this->returnSuccess('领取成功');
        }else{
            return $this->returnFail('领取失败');
        }
    }



}